
# Imports
import ss
import operator
import pickle
import base64
import time
import log

# Object representing a VM
# States: RUNNING, SNAPSHOTTING, MIGRATING, DEAD
class VM:

	# Constructor 
	def __init__(self):
		
		# Set up ID vars
		self.domID = -1
		
		# Set up state vars
		self.state = ""
		
		# Set up config vars
		self.domainCfgVars = {}
		self.imageCfgVars = {}
		self.networkCfgVars = []
		self.vbdCfgVars = []
		
		# Set up PM pointer
		self.myPM = None
		
		# Set up counters
		self.downCount = 0
		
		# Set up snapshot vars
		self.lastSnapshotTimestamp = 0
		self.snapshotList = []

	# Gets the hostname from the imageCfgVars['cmdline'] field
	def GetHostname(self):
		
		# Create a placeholder string
		myHostname = ''
		
		# Tokenize the cmdline field
		cmdChunks = self.imageCfgVars['cmdline'].split(':')
		
		# Iterate over chunks
		for cmdChunk in cmdChunks:
		
			# See if the word .edu is in this chunk - FIX ME !
			if '.edu' in cmdChunk:
			
				# Set
				myHostname = cmdChunk
				
				# Break
				break
				
		# Return
		return myHostname
	
	# Gets the root from the imageCfgVars['cmdline'] field
	def GetCfgRootField(self):
	
		# Create a placeholder string
		myRoot = ''
		
		# Tokenize the cmdline field
		cmdChunks = self.imageCfgVars['cmdline'].split(' ')
		
		# Iterate over chunks
		for cmdChunk in cmdChunks:
		
			# See if the word root is in this chunk
			if 'root' in cmdChunk:
				
				# Split again
				rootChunks = cmdChunk.split('=')
				
				# Set
				myRoot = rootChunks[1]
				
				# Break
				break
		
		# Return
		return myRoot
		
	# Gets the last snapshot object in the list
	def GetLastSnapshot(self):
		
		# Make sure we have snapshots
		if(len(self.snapshotList) > 0):
		
			# Sort by number
			self.snapshotList.sort(lambda x, y: cmp(x.version,y.version), reverse=True)
			
			# Return the top of the list
			return self.snapshotList[0]
		
		# Otherwise return null
		else:
			return None
		
	# Sets the last snapshot timestamp by parsing the list
	def GetLastSnapshotTimestamp(self):
		
		# Get last snapshot
		latestSnapshot = self.GetLastSnapshot()
		
		# Return the timestamp
		if latestSnapshot != None:
			return latestSnapshot.timestamp
		else:
			return None
	
	# Determines if this VM needs to be snapshotted
	def NeedsSnapshotting(self, freq):
		
		# Make sure we are running
		if self.state != "RUNNING":
			return False
		
		# Get latest snapshot timestamp and convert to a time
		latestTimestamp = self.GetLastSnapshotTimestamp()
		
		# Of we didnt get a snapshot just return true
		if latestTimestamp == None:
			return True
		
		# Calculate the difference
		diffTime = None
		diffTime = int(time.mktime(time.localtime()) - time.mktime(latestTimestamp))
		
		# Check and see if we should snapshot
		if diffTime >= freq:
			return True
		else:
			return False
		
	# Prints the VM details
	def Print(self):
		
		# Write IDs
		log.write( 'VM ' + self.domainCfgVars['uuid'] )
		log.write( 'IP = ' + self.IP )
		log.write( 'Name = ' + self.domainCfgVars['name'] )
		log.write( 'State = ' + self.state )
		
		# Write snapshots
		for thisSnapshot in self.snapshotList:
			log.write( '-> Snapshot #' + thisSnapshot.version + ' @ ' + thisSnapshot.GetTimestampString())
	

# Pickles a VM and then base64 encodes it
def PickleVM(myVM):
	
	# Pickle the VM
	pickledVM = pickle.dumps(myVM)
	
	# Base64 encode it
	pickledVMBase64 = base64.urlsafe_b64encode(pickledVM)
	
	# Return
	return pickledVMBase64

# Base64 decodes and then unpickles it
def UnPickleVM(pickledVMBase64):
	
	# Base64 decode it
	pickledVM = base64.urlsafe_b64decode(pickledVMBase64)
	
	# Unpickle it
	myVM = pickle.loads(pickledVM)
	
	# Return
	return myVM
